package com.zhiyou.app.shop.website.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.hibernate.metamodel.source.LocalBindingContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zhiyou.app.shop.common.BaseAction;
import com.zhiyou.app.shop.common.util.DateUtil;
import com.zhiyou.app.shop.common.util.ShopConstants;
import com.zhiyou.app.shop.website.dao.IPrizePayDao;
import com.zhiyou.app.shop.website.dao.pojo.DicItem;
import com.zhiyou.app.shop.website.dao.pojo.Loclist;
import com.zhiyou.app.shop.website.dao.pojo.Msg;
import com.zhiyou.app.shop.website.dao.pojo.News;
import com.zhiyou.app.shop.website.dao.pojo.PwdUpdateLog;
import com.zhiyou.app.shop.website.dao.pojo.User;
import com.zhiyou.app.shop.website.dao.pojo.UserAccount;
import com.zhiyou.app.shop.website.dao.pojo.UserBank;
import com.zhiyou.app.shop.website.service.IDicItemService;
import com.zhiyou.app.shop.website.service.ILoclistService;
import com.zhiyou.app.shop.website.service.IMsgService;
import com.zhiyou.app.shop.website.service.INewsService;
import com.zhiyou.app.shop.website.service.IUserAccountService;
import com.zhiyou.app.shop.website.service.IUserInfoService;
import com.zhiyou.app.shop.website.service.IUserManagerService;
import com.zhiyou.app.shop.website.util.EncryptData;
/**
 * @author sss
 * @create Time :2014-1-17
 */
public class UserManagerAction extends BaseAction {
	private static final long serialVersionUID = 4113704909427545844L;
	
	@Autowired
	private IUserManagerService userManagerService;
	@Autowired
	private ILoclistService loclistService;
	@Autowired
	private IDicItemService dicItemService;
	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private INewsService newsService;
	@Autowired
	private IMsgService msgService;
	@Autowired 
	private IUserInfoService userInfoService;

	
	private String registerType;  //注册类型 myself：为自己注册   other：为别人注册
	private String randStr;
	private User user;
	private String account;
	private UserBank userBank;
	private UserAccount userAccount;
	private List<Loclist> listCountry;
	private List<DicItem> locationList;
	private List<DicItem> levelList;
	private List<DicItem> bankList;
	private List<DicItem> mailList;
	private List<DicItem> newsList;
	private List<DicItem> enterTypelList;
	private List<User> userList;
	private String countryId;
	
	private String bankType;
	private String bankName1;
	private String bankName2;
	
	private String thirdPassword;
	private String password11;
	private String password21;
	private String password31;
	
	private String tolevel; //升级到
	
	private BigDecimal vvPrize;
	
	private JsonArray treedata = new JsonArray();
	private String reAccount;
	
	private String id;//新闻或消息的id
	
	private String parentId;
	private String location;
	
	private Integer floor;
	
	public String member(){
		return SUCCESS;
	}
	
	public String myself(){
		randStr = userManagerService.getGeneralAccount();
		locationList = dicItemService.findByType(ShopConstants.LOCATION);
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		user = (User) getSession().get(ShopConstants.LOGIN_USER);
		user.setParentId(parentId);
		user.setLocation(location);
		List<UserBank> listUserBank = userManagerService.getUserBankByUid(user.getUserAccount());
		if(listUserBank != null && listUserBank.size()>0){
			userBank = listUserBank.get(0);			
		}
		return SUCCESS;
	}
	
	public String other(){
		locationList = dicItemService.findByType(ShopConstants.LOCATION);
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		bankList = dicItemService.findByType(ShopConstants.BANK_TYPE);		
		listCountry = loclistService.getConutry();
		randStr = userManagerService.getGeneralAccount();
		enterTypelList = dicItemService.findByType(ShopConstants.ENTER_TYPE);
		return SUCCESS;
	}
	
	
	/**
	 * 注册页面
	 * @return
	 */
	public String registerPage(){
		return SUCCESS;
	}
	
	private String newUserName;
	public String register(){
		User curUser = (User) getSession().get(ShopConstants.LOGIN_USER);
		user.setFlag(ShopConstants.TRUE);
		user.setRole(ShopConstants.MEMBER);
		user.setCreditLevel("5");
		user.setRegisterDate(new Timestamp(System.currentTimeMillis()));
		user.setSparel(0);
		user.setSparelAmount(new BigDecimal(0));
		user.setSparer(0);
		user.setApaerAmount(new BigDecimal(0));
		user.setRecommendCnt("0");
		user.setLeftLeave(0);
		user.setLeftLeaveAmount(new BigDecimal(0));
		user.setRightLeave(0);
		user.setRightLeaveAmount(new BigDecimal(0));
		String type = "";
		if("myself".equals(registerType)){//为自己注册    加单     加单费用扣除附属账户的
			type = "myself";
			user.setFirstPwd(curUser.getFirstPwd());
			user.setSecondPwd(curUser.getSecondPwd());
			user.setThirdPwd(curUser.getThirdPwd());
			user.setRecommendId(curUser.getUserAccount());
			user.setMainAccount(curUser.getUserAccount());
			user.setEnterType("2"); //加单
			
			UserBank anotherUserBank = new UserBank();
			List<UserBank> listUserBank = userManagerService.getUserBankByUid(curUser.getUserAccount());
			userBank = new UserBank();
			if(listUserBank != null && listUserBank.size()>0){
				anotherUserBank = listUserBank.get(0);	
				BeanUtils.copyProperties(anotherUserBank,userBank);
			}
			userBank.setId(null);
		}else{  //为别人注册
			user.setEnterType("1");//报单
			user.setFirstPwd(encodePassword(user.getFirstPwd()));
			user.setSecondPwd(encodePassword(user.getSecondPwd()));
			user.setThirdPwd(encodePassword(user.getThirdPwd()));
			if("1".equals(bankType)){//从给定的银行中选
				userBank.setBankName(bankName1);
			}else{ //自定义银行
				userBank.setBankName(bankName2);
			}
		}
		userManagerService.saveUserAndBank(user, userBank,type);
		setNewUserName(user.getUserAccount());

		return check();
	}
	
	/**
	 * 审核 页面
	 * @return
	 */
	public String check(){
		locationList = dicItemService.findByType(ShopConstants.LOCATION);
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		userAccount = userAccountService.findUserAccount(getCurrentUser().getUserAccount());
		pageSize = 8;
		userManagerService.getCheckUser(getInitedPage(), getCurrentUser().getUserAccount());
		return SUCCESS;
	}
	/**
	 * 删除未激活的用户
	 */
	public String deleteUser(){
		User user  = userManagerService.getUserById(id);
		userManagerService.deleteUser(user);
		return check();
	}
	
	/**
	 * 用户激活
	 * 
	 * @return
	 */
	public String activityUser(){
		try {
			User curUser = getCurrentUser();
			User ActedUser = userManagerService.getUserById(user.getUserId());
			int result = 3;
			try {
				result = userManagerService.auditUser(getCurrentUser().getUserAccount(),ActedUser.getUserId());
				if(result == 0){
					//httpclient xmpp用户注册  xmpp createUser
					DicItem dicItem = dicItemService.findByTypeAndCode(ShopConstants.XMPP, "0");
					//String xmppurl = "http://"+dicItem.getName()+"/plugins/microplugin/microplugin";
					String xmppurl = "http://"+dicItem.getName()+"/MobileAdmin/iface/user/registerjj.shtml";
					try {
						HttpPost post = new HttpPost(xmppurl);
						//添加参数
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("nickname", ActedUser.getUserAccount().toLowerCase()));
						params.add(new BasicNameValuePair("password", ActedUser.getFirstPwd()));
						params.add(new BasicNameValuePair("attr1", "1"));
						post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
						//发送请求
						HttpClient http = new DefaultHttpClient();
						HttpResponse response = http.execute(post);
						HttpEntity entity = response.getEntity();
						System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
						System.out.println(response.getStatusLine().getStatusCode());
						if(response.getStatusLine().getStatusCode() == 200){
							String results = EntityUtils.toString(response.getEntity());
							//得到返回的字符串
							//System.out.println(results);
							//JsonObject jo = new JsonObject();
							//打印输出
							//如果是下载文件,可以用response.getEntity().getContent()返回InputStream
						}
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
					//end xmpp createUser
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			getResponse().setContentType("text/html; charset=UTF-8");
			getResponse().getWriter().print(result+"");
			getResponse().getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 查看用户信息
	 */
	public String userInfo(){
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		List<UserBank> listUserBank = userManagerService.getUserBankByUid(getCurrentUser().getUserAccount());
		if(listUserBank != null && listUserBank.size()>0){
			userBank = listUserBank.get(0);			
		}
		return SUCCESS;
	}
	
	/**
	 * 会员升级页面
	 * @return
	 */
	public String up(){
		try {
			levelList = dicItemService.findByType(ShopConstants.LEVEL);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String promoted(){
		getResponse().setContentType("text/html; charset=UTF-8");
		int flag = userManagerService.promote(getCurrentUser().getUserId(), tolevel);
		String msg = "";
		if(flag == 0 ){
			msg = "升级成功!";
			getCurrentUser().setLevel(tolevel);
		}else if(flag == 1){
			msg = "激活豆不足 升级失败!";
		}else if(flag == 2){
			msg = "操作失败，请重试!";
		}
		try {
			getResponse().getWriter().print(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	public String password(){
		
		return SUCCESS;
	}
	
	public String savePwd(){
		getResponse().setContentType("text/html; charset=UTF-8");
		PwdUpdateLog pwd1 =null;
		PwdUpdateLog pwd2 =null;
		PwdUpdateLog pwd3 =null;
		Timestamp time = new Timestamp(System.currentTimeMillis());
		try {
			User user = userManagerService.getUserById(getCurrentUser().getUserId());
			if(!"".equals(password11)){  //一级密码
				pwd1 = new PwdUpdateLog();
				pwd1.setUserId(getCurrentUser().getUserAccount());
				pwd1.setOld(user.getFirstPwd());
				pwd1.setNews(password11);
				pwd1.setUpdateTime(time);
				pwd1.setType("1");
				pwd1.setUpdateBy(getCurrentUser().getUserAccount());
				pwd1.setIpAddress(getIpAddr(getRequest()));
				//pwd1.setIpAddress(ipAddress);
				user.setFirstPwd(encodePassword(password11));
				
				DicItem dicItem = dicItemService.findByTypeAndCode(ShopConstants.XMPP, "0");
				String xmppurl = "http://"+dicItem.getName()+"/MobileAdmin/iface/user/changeUserPwd.shtml";
				try {
					HttpPost post = new HttpPost(xmppurl);
					//添加参数
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("nickname", user.getUserAccount().toLowerCase()));
					params.add(new BasicNameValuePair("password", encodePassword(password11)));
					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					//发送请求
					HttpClient http = new DefaultHttpClient();
					HttpResponse response = http.execute(post);
					/*HttpEntity entity = response.getEntity();
					System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
					System.out.println(response.getStatusLine().getStatusCode());*/
					if(response.getStatusLine().getStatusCode() == 200){
						/*String results = EntityUtils.toString(response.getEntity());
						Gson gson = new Gson();
						JsonArray array = new JsonArray();*/
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(!"".equals(password21)){
				pwd2 = new PwdUpdateLog();
				pwd2.setUserId(getCurrentUser().getUserAccount());
				pwd2.setOld(user.getSecondPwd());
				pwd2.setNews(password21);
				pwd2.setUpdateTime(time);
				pwd2.setType("2");
				pwd2.setUpdateBy(getCurrentUser().getUserAccount());
				pwd2.setIpAddress(getIpAddr(getRequest()));
				user.setSecondPwd(encodePassword(password21));
			}
			if(!"".equals(password31)){
				pwd3 = new PwdUpdateLog();
				pwd3.setUserId(getCurrentUser().getUserAccount());
				pwd3.setOld(user.getThirdPwd());
				pwd3.setNews(password31);
				pwd3.setUpdateTime(time);
				pwd3.setType("3");
				pwd3.setUpdateBy(getCurrentUser().getUserAccount());
				pwd3.setIpAddress(getIpAddr(getRequest()));
				user.setThirdPwd(encodePassword(password31));
			}
			//userManagerService.saveUser(user);
			userInfoService.savePwd(user, pwd1, pwd2, pwd3);
			getCurrentUser().setFirstPwd(user.getFirstPwd());
			getCurrentUser().setSecondPwd(user.getSecondPwd());
			getCurrentUser().setThirdPwd(user.getThirdPwd());
			PrintWriter out = getResponse().getWriter();
			out.print("修改密码成功!");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	private String getIpAddr(HttpServletRequest request) { 
	       String ip = request.getHeader("x-forwarded-for"); 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       return ip; 
	   } 

	/**
	 * 修改银行账户
	 * @return
	 */
	public String bankpw(){
		user = getCurrentUser();
		listCountry = loclistService.getConutry();
		List<UserBank> listUserBank = userManagerService.getUserBankByUid(user.getUserAccount());
		if(listUserBank != null && listUserBank.size()>0){
			userBank = listUserBank.get(0);			
		}
		return SUCCESS;
	}
	
	public String saveBankpw(){
		getResponse().setContentType("text/html; charset=UTF-8");
		try {
			List<UserBank> listUserBank = userManagerService.getUserBankByUid(getCurrentUser().getUserAccount());
			if (listUserBank != null && listUserBank.size() > 0) {
				UserBank bank = listUserBank.get(0);
				bank.setBankCountry(userBank.getBankCountry());
				//bank.setBankUser(userBank.getBankUser());
				bank.setBankProvince(userBank.getBankProvince());
				bank.setSubBranch(userBank.getSubBranch());
				bank.setBankCard(userBank.getBankCard());
				bank.setBankName(userBank.getBankName());
				userManagerService.saveUserBank(bank);
			}
			PrintWriter out = getResponse().getWriter();
			out.print("修改银行信息成功!");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String vvAccounts(){
		userList = userManagerService.getVvUser(getCurrentUser().getUserAccount());
		userAccount = userAccountService.findUserAccount(getCurrentUser().getUserAccount());
		//vvPrize = userManagerService.getVvPrize(userList);
		locationList = dicItemService.findByType(ShopConstants.LOCATION);
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		return SUCCESS;
	}
	//推荐图
	public String recommend(){
		User user = getCurrentUser();
		
		//根节点是当前用户
		JsonObject po = new JsonObject();
		po.addProperty("id", user.getUserAccount());
		po.addProperty("pId", "0");
		System.out.println();
		po.addProperty("name", "会员ID："+user.getUserAccount()+"，级别："+user.getLevel()+"，类型："+((ShopConstants.TRUE.equals(user.getActivity()))?ShopConstants.FULL_MEMBER:ShopConstants.NON_MEMBER)+"，直接下属："+userManagerService.getRecommendCnt(user.getUserAccount()));
		po.addProperty("open", true);
		treedata.add(po);
		List<User> recommendList = userManagerService.getRecommend(user.getUserAccount());
		/*List<User> recommendList = new ArrayList<User>();
		recommendList = findUser(recommendList, user.getUserAccount());*/
		for (User recommend : recommendList) {
			JsonObject o = new JsonObject();
			int cnt = userManagerService.getRecommendCnt(recommend.getUserAccount());
			o.addProperty("id", recommend.getUserAccount());
			o.addProperty("pId", recommend.getRecommendId());
			o.addProperty("name", "会员ID："+recommend.getUserAccount()+"，级别："+recommend.getLevel()+"，类型："+((ShopConstants.TRUE.equals(recommend.getActivity()))?ShopConstants.FULL_MEMBER:ShopConstants.NON_MEMBER)+"，直接下属："+userManagerService.getRecommendCnt(recommend.getUserAccount()));
			if(cnt > 0){
				o.addProperty("isParent", true);						
			}
			treedata.add(o);
		}
		return SUCCESS;
	}
	public String findChild(){
		//isParent
		getResponse().setContentType("text/html; charset=UTF-8");
		try {
			JsonArray treedata = new JsonArray ();
			List<User> recommendList = userManagerService.getRecommend(reAccount);
			if(recommendList != null && recommendList.size() >0){
				for (User recommend : recommendList) {
					JsonObject o = new JsonObject();
					int cnt = userManagerService.getRecommendCnt(recommend.getUserAccount());
					o.addProperty("id", recommend.getUserAccount());
					o.addProperty("pId", recommend.getRecommendId());
					o.addProperty("name", "会员ID："+recommend.getUserAccount()+"，级别："+recommend.getLevel()+"，类型："+((ShopConstants.TRUE.equals(recommend.getActivity()))?ShopConstants.FULL_MEMBER:ShopConstants.NON_MEMBER)+"，直接下属："+cnt);
					if(cnt > 0){
						o.addProperty("isParent", true);						
					}
					treedata.add(o);
				}			
			}
			getResponse().getWriter().print(treedata);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private List<User> findUser(List<User> list, String userAccount){
		List<User> childList = userManagerService.getRecommend(userAccount);
		if(childList != null && childList.size() > 0){
			list.addAll(childList);
			for (User user : childList) {
				findUser(list, user.getUserAccount());
			}
		}
		return list;
	}
	
	/**
	 * 人事关系图
	 */
	/*public String relation(){
		user = getCurrentUser();
		//向下查3层
		
		//userManagerService
		return SUCCESS;
	}*/
	
	/********************************************************************/
	public String relation(){
		User user = null;
		if(id == null || "".equals(id)){
			user = getCurrentUser();			
		}else{
			user = userManagerService.getUserById(id);
		}
		if(floor == null || "".equals(floor))
			floor = 3;
		location = test1(user,floor);
		return SUCCESS;
	}
	
	private String test1(User user,int floor){//递归取
		StringBuilder result = new StringBuilder("<table border='0'><tr align='center'><td colspan='2'>"+test2(user)+"</td></tr>");
		floor -= 1;
		if(floor >0){
			result.append(test3());
			List<User> users = userManagerService.getRedirectChild(user.getUserAccount());
			result.append("<tr valign ='top'>");
			if(users == null || users.size() ==0){ //没有子节点
				result.append("<td>"+test4(user,"1")+"</td>");
				result.append("<td>"+test4(user,"2")+"</td>");
			}else if(users.size() ==1){ //有一个子节点
				//判断左边还是右边
				if("1".equals(users.get(0).getLocation())){  //左边
					result.append("<td>"+test1(users.get(0),floor)+"</td>");
					result.append("<td>"+test4(user,"2")+"</td>");
				}else{  //右边
					result.append("<td>"+test4(user,"1")+"</td>");
					result.append("<td>"+test1(users.get(0),floor)+"</td>");
				}
				
			}else{
				for(User u:users){
					result.append("<td>"+test1(u,floor)+"</td>");
				}				
			}
		}
		result.append("</tr>");
		result.append("</table>");
		return result.toString();
	}
	
	private String test2(User  u){
		String activityFlag = u.getActivity();
		if(activityFlag == null || "".equals(activityFlag)){
			activityFlag = "(未激活)";			
		}else{
			activityFlag = "";
		}
		String level = dicItemService.findByTypeAndCode(ShopConstants.LEVEL, u.getLevel()).getName();
		StringBuilder result = new StringBuilder("<table border='0' width='200' cellpadding='0' cellspacing='1' bgcolor='#cacaca'><tr><td colspan='2' bgcolor='#f0f0f0' class='rs'><a href='relation.action?id="+u.getUserId()+"'>"+u.getUserAccount()+"</a>"+activityFlag+"</td></tr>"
				+ "<tr><td colspan='2' bgcolor='#FFFFFF' class='rs'>"+level+"</td></tr>"
				+ "<tr><td colspan='2' bgcolor='#FFFFFF' class='rs'>"+DateUtil.getDate(u.getRegisterDate(), "yyyy-M-dd hh:mm:ss")+"</td></tr>"
				+ "<tr><td bgcolor='#FFFFFF' class='rs'>"+u.getSparelAmount().intValue()+"("+u.getSparel()+")</td>" 
				+     "<td bgcolor='#FFFFFF' class='rs'>"+u.getApaerAmount().intValue()+"("+u.getSparer()+")</td></tr>"
				+ "<tr><td bgcolor='#FFFFFF' class='rs'>"+u.getLeftLeaveAmount().intValue()+"("+u.getLeftLeave()+")</td>"
				+     "<td bgcolor='#FFFFFF' class='rs'>"+u.getRightLeaveAmount().intValue()+"("+u.getRightLeave()+")</td></tr></table>");	
		return result.toString();
	}
	
	private String test4(User u,String location){
		String activityFlag = u.getActivity();
		if(activityFlag == null || "".equals(activityFlag)){//父节点未激活  不能注册
			activityFlag = "";			
		}else{  
			activityFlag = "<a href='member.action?parentId="+u.getUserAccount()+"&location="+location+"'>注册</a>";
		}
		StringBuilder result = new StringBuilder("<table border='0'><tr align='center'><td colspan='2'>  "
					+"<table width='200' border='0' cellpadding='0' cellspacing='1' bgcolor='#ed1b2f'>"
					+"<tr><td height='24' style='text-align:center; color:#fff;'>"+activityFlag+"</td></tr>"
					+"<tr><td height='100' bgcolor='#FFFFFF'>&nbsp;</td></tr></table></td></tr></table>");
		return result.toString();
	}
	
	private String test3(){//划线Z
		/*StringBuilder result = new StringBuilder("<tr><td align='center' colspan='2'><img height='20' src='"+getRequest().getContextPath()+"/resources/images/t_tree_top.gif'/></td></tr>");
		result.append("<tr><td><img width='25%' height='20' align='right' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif'/></td>" +
				"<td><img width='25%' height='20' align='left' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif'/></td></tr>");
		
		result.append("<tr><td><img height='25' align='center' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_l.gif' complete='complete'/></td>" +
				"<td><img height='25' align='center' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_r.gif' complete='complete'/></td></tr>");*/
		StringBuilder result = new StringBuilder();
		result.append("<tr><td width='100%' align='center' colspan='2' valign ='top'>" +
				"<img height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_l.gif' complete='complete'/>"
				+"<img width='25%' height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif' complete='complete'/>"
				+"<img height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_top.gif' complete='complete'/>"
				+"<img width='25%' height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif' complete='complete'/>"
				+"<img height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_r.gif'/></td></tr>");
		return result.toString();
	}

	
	
	
	
	/*******************************************************************/
	
	private Msg msg;
	/**
	 * 邮件  消息
	 * @return
	 */
	public String tomail(){
		mailList = dicItemService.findByType(ShopConstants.MAIL_TYPE);
		return SUCCESS;
	}
	
	public String saveMail(){
		msg.setCreateDate(new Timestamp(System.currentTimeMillis()));
		msg.setFlag(ShopConstants.TRUE);
		msg.setIsRead(ShopConstants.FALSE);
		msg.setSendId(getCurrentUser().getUserAccount());
		msgService.sendMsg(msg);
		return SUCCESS;
	}
	
	public String information(){
		pageSize = 10;
		msgService.findReceiveMsg(getInitedPage(), getCurrentUser().getUserAccount());
		return SUCCESS;
	}
	
	public String inbox(){
		pageSize = 10;
		msgService.findReceiveMsg(getInitedPage(), getCurrentUser().getUserAccount());
		return SUCCESS;
	}
	
	public String sent(){
		pageSize = 10;
		msgService.findsendMsg(getInitedPage(), getCurrentUser().getUserAccount());
		return SUCCESS;
	}
	
	private News news;
	/**
	 * 新闻 公告
	 * @return
	 */
	public String news(){
		newsService.getNews(getInitedPage());
		return SUCCESS;
	}
	public String notice(){
		newsService.getNewsByType(getInitedPage(), "2");
		return SUCCESS;
	}
	public String toNews(){
		newsList = dicItemService.findByType(ShopConstants.NEWS_TYPE);
		
		return SUCCESS;
	}
	public String saveNews(){
		news.setCreateDate(new Timestamp(System.currentTimeMillis()));
		news.setFlag(ShopConstants.TRUE);
		news.setWriterId(getCurrentUser().getUserId());
		newsService.saveNews(news);
		return SUCCESS;
	}
	
	public String msgInfo(){		
		mailList = dicItemService.findByType(ShopConstants.MAIL_TYPE);
		msg = msgService.findById(id);
		msg.setIsRead(ShopConstants.TRUE);
		msg.setReadDate(new Timestamp(new Date().getTime()));
		msgService.update(msg);
		return SUCCESS;
	}
	
	public String newsInfo(){
		newsList = dicItemService.findByType(ShopConstants.NEWS_TYPE);
		news = newsService.findById(id);
		return SUCCESS;
	}
	
	//回复邮件
	public String replyMsg(){
		mailList = dicItemService.findByType(ShopConstants.MAIL_TYPE);
		msg = msgService.findById(id);
		msg.setTitle("答复："+msg.getTitle());
		return SUCCESS;
	}
	
	/**
	 * 账号生成  MY+7位随机数字
	 * 1000000---9999999
	 * @return
	 */
	public String GeneralNum(){
		randStr = userManagerService.getGeneralAccount();
		try {
			getResponse().getWriter().print(randStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String checkLocation(){
		getResponse().setContentType("text/html; charset=UTF-8");
		List<User> parentUser = userManagerService.getUser(user.getParentId());
		List<User> recommendUser = userManagerService.getUser(user.getRecommendId());
		if(recommendUser == null || recommendUser.size()==0){
			try {
				getResponse().getWriter().print("该推荐人不存在，请填写正确的推荐人!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if(parentUser == null || parentUser.size()==0){
			try {
				getResponse().getWriter().print("该安置人不存在，请填写正确的安置人!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			List<User> userList = userManagerService.checkParentAndLoc(user.getParentId(), user.getLocation());
			if(userList != null && userList.size() > 0){
				try {
					getResponse().getWriter().print("该安置人的位置已经被占用，请选择其他位置!");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		return null;
	}

	public String getProvince(){
		getResponse().setContentType("text/html; charset=UTF-8");
		if (!"".equals(countryId)) {
			List provinces = loclistService.findAllProvinceByContry(countryId);
			StringBuffer jsonReturn = new StringBuffer("");
			jsonReturn.append("<option value=\"\">--请选择省市--</option>");
			if(provinces != null && provinces.size() >0){
				for (int i = 0; i < provinces.size(); i++) {
					Loclist loclist = (Loclist) provinces.get(i);
					if(loclist != null){
						String loc = "<option value=\"" + loclist.getId().getF6() + "\">"
								+ loclist.getId().getF6() + "</option>";
						jsonReturn.append(loc);						
					}
				}
			}
			// System.out.println(jsonReturn);
			try {
				getResponse().getWriter().print(jsonReturn);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				getResponse().getWriter().print("<option value=\"\">--请选择省市--</option>");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public String checkThirdPwd(){
		getResponse().setContentType("text/html; charset=UTF-8");
		User user = getCurrentUser();
		if(!user.getThirdPwd().equals(encodePassword(thirdPassword))){
			try {
				getResponse().getWriter().print("原来三级密码输入错误!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public String checkUserExist(){
		getResponse().setContentType("text/html; charset=UTF-8");
		List<User> userList = userManagerService.getUser(account);
		if(userList == null || userList.size() ==0){
			try {
				getResponse().getWriter().print("输入的账户无效，请重写输入!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public String getRegisterType() {
		return registerType;
	}
	

	public void setRegisterType(String registerType) {
		this.registerType = registerType;
	}

	public String getRandStr() {
		return randStr;
	}

	public void setRandStr(String randStr) {
		this.randStr = randStr;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<Loclist> getListCountry() {
		return listCountry;
	}

	public void setListCountry(List<Loclist> listCountry) {
		this.listCountry = listCountry;
	}

	public String getCountryId() {
		return countryId;
	}

	public void setCountryId(String countryId) {
		this.countryId = countryId;
	}

	public List<DicItem> getLocationList() {
		return locationList;
	}

	public void setLocationList(List<DicItem> locationList) {
		this.locationList = locationList;
	}

	public List<DicItem> getLevelList() {
		return levelList;
	}

	public void setLevelList(List<DicItem> levelList) {
		this.levelList = levelList;
	}

	public List<DicItem> getBankList() {
		return bankList;
	}

	public void setBankList(List<DicItem> bankList) {
		this.bankList = bankList;
	}

	public UserBank getUserBank() {
		return userBank;
	}

	public void setUserBank(UserBank userBank) {
		this.userBank = userBank;
	}

	public String getBankType() {
		return bankType;
	}

	public void setBankType(String bankType) {
		this.bankType = bankType;
	}

	public String getBankName1() {
		return bankName1;
	}

	public void setBankName1(String bankName1) {
		this.bankName1 = bankName1;
	}

	public String getBankName2() {
		return bankName2;
	}

	public void setBankName2(String bankName2) {
		this.bankName2 = bankName2;
	}

	public UserAccount getUserAccount() {
		return userAccount;
	}

	public void setUserAccount(UserAccount userAccount) {
		this.userAccount = userAccount;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public String getTolevel() {
		return tolevel;
	}

	public void setTolevel(String tolevel) {
		this.tolevel = tolevel;
	}

	public String getPassword11() {
		return password11;
	}

	public void setPassword11(String password11) {
		this.password11 = password11;
	}

	public String getPassword21() {
		return password21;
	}

	public void setPassword21(String password21) {
		this.password21 = password21;
	}

	public String getPassword31() {
		return password31;
	}

	public void setPassword31(String password31) {
		this.password31 = password31;
	}

	public String getThirdPassword() {
		return thirdPassword;
	}

	public void setThirdPassword(String thirdPassword) {
		this.thirdPassword = thirdPassword;
	}

	public BigDecimal getVvPrize() {
		return vvPrize;
	}

	public void setVvPrize(BigDecimal vvPrize) {
		this.vvPrize = vvPrize;
	}

	public JsonArray getTreedata() {
		return treedata;
	}

	public void setTreedata(JsonArray treedata) {
		this.treedata = treedata;
	}

	public List<DicItem> getMailList() {
		return mailList;
	}

	public void setMailList(List<DicItem> mailList) {
		this.mailList = mailList;
	}

	public List<DicItem> getNewsList() {
		return newsList;
	}

	public void setNewsList(List<DicItem> newsList) {
		this.newsList = newsList;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public Msg getMsg() {
		return msg;
	}

	public void setMsg(Msg msg) {
		this.msg = msg;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getReAccount() {
		return reAccount;
	}

	public void setReAccount(String reAccount) {
		this.reAccount = reAccount;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<DicItem> getEnterTypelList() {
		return enterTypelList;
	}

	public void setEnterTypelList(List<DicItem> enterTypelList) {
		this.enterTypelList = enterTypelList;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public Integer getFloor() {
		return floor;
	}

	public void setFloor(Integer floor) {
		this.floor = floor;
	}

	public String getNewUserName() {
		return newUserName;
	}

	public void setNewUserName(String newUserName) {
		this.newUserName = newUserName;
	}
	
}
